import { defineStore } from 'pinia'
import axios from 'axios'

export const useChecksStore = defineStore('checks', {
  state: () => ({
    checks: [],
    loading: false,
    error: null
  }),
  
  actions: {
    async fetchChecks() {
      this.loading = true
      this.error = null
      
      try {
        const response = await axios.get('/getAllChecks')
        this.checks = response.data
      } catch (error) {
        this.error = error.response?.data?.message || 'Failed to fetch checks'
        console.error('Error fetching checks:', error)
      } finally {
        this.loading = false
      }
    },
    
    async addCheck(check) {
      this.loading = true
      this.error = null
      
      try {
        await axios.post('/insertChecks', check)
        await this.fetchChecks()
      } catch (error) {
        this.error = error.response?.data?.message || 'Failed to add check'
        console.error('Error adding check:', error)
      } finally {
        this.loading = false
      }
    },
    
    async updateCheck(check) {
      this.loading = true
      this.error = null
      
      try {
        await axios.post('/updateChecks', check)
        await this.fetchChecks()
      } catch (error) {
        this.error = error.response?.data?.message || 'Failed to update check'
        console.error('Error updating check:', error)
      } finally {
        this.loading = false
      }
    },
    
    async deleteCheck(chId) {
      this.loading = true
      this.error = null
      
      try {
        await axios.get(`/deleteChecks/${chId}`)
        await this.fetchChecks()
      } catch (error) {
        this.error = error.response?.data?.message || 'Failed to delete check'
        console.error('Error deleting check:', error)
      } finally {
        this.loading = false
      }
    }
  }
})

// Create an alias export for useCheckStore to maintain compatibility with existing code
export const useCheckStore = useChecksStore; 